package JavaEE_1;

import java.io.*;
import java.util.Scanner;

//扫描指定⽬录，并找到名称或者内容中包含指定字符的所有普通⽂件
public class FileDomo {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入待搜索的目录");
        String file = scanner.next();
        File mainfile = new File(file);
        if(!mainfile.isDirectory())
        {
            System.out.println("不是目录");
            return;
        }
        System.out.println("请输入待查找的字符");
        String taget = scanner.next();
        searchdir(mainfile,taget);

    }

    private static void searchdir(File mainfile, String taget) {
        File[] files = mainfile.listFiles();
        if(files==null)
        {
            return;
        }
        for (File file:files
             ) {
            if(file.isFile()){
                dealfile(file,taget);
            }
            else {
                searchdir(file,taget);
            }

        }

    }

    private static void dealfile(File file, String taget){
        if(file.getName().contains(taget))
        {
            System.out.println("名字包含"+file.getName());
        }
        StringBuffer stringBuffer = new StringBuffer();
        try (Reader reader = new FileReader(file)){
           char[] chars = new char[1024];
            int n = reader.read(chars);
            if(n==-1){
                return;
            }
            stringBuffer.append(chars,0,n);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(stringBuffer.indexOf(taget)>=0)
        {
            System.out.println("文件内容含有"+file.getAbsolutePath());
        }
        return;

    }
}
